# -*- coding: utf-8 -*- 
"""
This demo demonstrates how to draw a dynamic mpl (matplotlib) 
plot in a wxPython application.

It allows "live" plotting as well as manual zooming to specific
regions.

Both X and Y axes allow "auto" or "manual" settings. For Y, auto
mode sets the scaling of the graph to see all the data points.
For X, auto mode makes the graph "follow" the data. Set it X min
to manual 0 to always see the whole data from the beginning.

Note: press Enter in the 'manual' text box to make a new value 
affect the plot.

Eli Bendersky (eliben@gmail.com)
License: this code is in the public domain
Last modified: 31.07.2008
"""
import os
import pprint
import random
import sys
import wx
import wx.grid
import csv

# The recommended way to use wx with mpl is with the WXAgg
# backend. 
#
import matplotlib
from matplotlib.dates import strpdate2num
from wx._core import Size
from wxPython._controls import wxScrollBar
matplotlib.use('WXAgg')
import matplotlib.dates as mdates
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import \
    FigureCanvasWxAgg as FigCanvas, \
    NavigationToolbar2WxAgg as NavigationToolbar
import numpy as np
import pylab

class CSVFileDataSource():
    def __init__(self, file_path):
        self.rows = []
        self.lines = {}
        self.table = []
        with open(file_path, 'r') as f:
            reader = csv.reader(f, delimiter=',', quotechar='"')
            i = 0
            for row in reader:
                if i > 0: #Skip first row with metadata
                    value = None
                    key = None
                    timestamp = None
                    user = None
                    process = None
                    if len(row) == 3:
                        self.rows.append(float(row[2]))
                        value = float(row[2])
                        key = row[1]
                        timestamp = row[0]
                    elif len(row) == 5:
                        self.rows.append(float(row[4]))
                        value = float(row[4])
                        key = row[1] + ' filtered'
                        timestamp = row[0]
                        process = row[2]
                        user = row[3]
                    if not value is None :
                        if self.lines.has_key(key) :
                            if self.lines[key].has_key(timestamp):
                                self.lines[key][timestamp] += value
                                self.rows.append(self.lines[key][timestamp])
                            else:
                                self.lines[key][timestamp] = value 
                        else :
                            self.lines[key] = { timestamp : value}
                        self.table.append((timestamp, key, value, user, process))
                i = i + 1 
        
class BoundControlBox(wx.Panel):
    """ A static box with a couple of radio buttons and a text
        box. Allows to switch between an automatic mode and a 
        manual mode with an associated value.
    """
    def __init__(self, parent, ID, label, initval):
        wx.Panel.__init__(self, parent, ID)
        
        self.value = initval
        
        box = wx.StaticBox(self, -1, label)
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        
        self.radio_auto = wx.RadioButton(self, -1, 
            label="Auto", style=wx.RB_GROUP)
        self.radio_manual = wx.RadioButton(self, -1,
            label="Manual")
        self.manual_text = wx.TextCtrl(self, -1, 
            size=(35,-1),
            value=str(initval),
            style=wx.TE_PROCESS_ENTER)
        
        self.Bind(wx.EVT_UPDATE_UI, self.on_update_manual_text, self.manual_text)
        self.Bind(wx.EVT_TEXT_ENTER, self.on_text_enter, self.manual_text)
        
        manual_box = wx.BoxSizer(wx.HORIZONTAL)
        manual_box.Add(self.radio_manual, flag=wx.ALIGN_CENTER_VERTICAL)
        manual_box.Add(self.manual_text, flag=wx.ALIGN_CENTER_VERTICAL)
        
        sizer.Add(self.radio_auto, 0, wx.ALL, 10)
        sizer.Add(manual_box, 0, wx.ALL, 10)
        
        self.SetSizer(sizer)
        sizer.Fit(self)
    
    def on_update_manual_text(self, event):
        self.manual_text.Enable(self.radio_manual.GetValue())
    
    def on_text_enter(self, event):
        self.value = self.manual_text.GetValue()
    
    def is_auto(self):
        return self.radio_auto.GetValue()
        
    def manual_value(self):
        return self.manual_text.GetValue()


class GraphFrame(wx.Frame):
    """ The main frame of the application
    """
    DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
    
    def __init__(self, parent, file_name = None, title = 'Wykres zużycia zasobów'):
        wx.Frame.__init__(self, parent, -1, title)
        
        if file_name is not None:
            self.data_source = CSVFileDataSource(file_name)
            self.data = self.data_source.rows
            self.lines = self.data_source.lines
            self.paused = True
        
        self.create_menu()
        self.create_status_bar()
        self.create_main_panel()
        self.draw_plot()
        

    def create_menu(self):
        self.menubar = wx.MenuBar()
        
        menu_file = wx.Menu()
        m_expt = menu_file.Append(-1, "Zapisz\tCtrl-S", "Zapisz do pliku")
        self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt)
        menu_file.AppendSeparator()
        m_exit = menu_file.Append(-1, "Wyjdź\tCtrl-X", "Wyjdź")
        self.Bind(wx.EVT_MENU, self.on_exit, m_exit)
                
        self.menubar.Append(menu_file, "Plik")
        self.SetMenuBar(self.menubar)

    def create_main_panel(self):
        self.panel = wx.Panel(self)

        self.init_plot()
        self.canvas = FigCanvas(self.panel, -1, self.fig)

        self.xmin_control = BoundControlBox(self.panel, -1, "X min", 0)
        self.xmax_control = BoundControlBox(self.panel, -1, "X max", 50)
        self.ymin_control = BoundControlBox(self.panel, -1, "Y min", 0)
        self.ymax_control = BoundControlBox(self.panel, -1, "Y max", 100)
        
        self.pause_button = wx.Button(self.panel, -1, "Odśwież")
        self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button)
        self.canvas.Bind(wx.EVT_LEFT_DOWN, self.on_click_down)
        self.canvas.Bind(wx.EVT_LEFT_UP, self.on_click_up)
        #self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button)
        
        self.cb_grid = wx.CheckBox(self.panel, -1, 
            "Show Grid",
            style=wx.ALIGN_RIGHT)
        self.Bind(wx.EVT_CHECKBOX, self.on_cb_grid, self.cb_grid)
        self.cb_grid.SetValue(True)
        
        self.cb_xlab = wx.CheckBox(self.panel, -1, 
            "Show X labels",
            style=wx.ALIGN_RIGHT)
        self.Bind(wx.EVT_CHECKBOX, self.on_cb_xlab, self.cb_xlab)        
        self.cb_xlab.SetValue(True)
        
        self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        self.hbox1.AddSpacer(20)
        self.hbox1.Add(self.cb_grid, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.cb_xlab, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        
        self.hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox2.Add(self.xmin_control, border=5, flag=wx.ALL)
        self.hbox2.Add(self.xmax_control, border=5, flag=wx.ALL)
        self.hbox2.AddSpacer(24)
        self.hbox2.Add(self.ymin_control, border=5, flag=wx.ALL)
        self.hbox2.Add(self.ymax_control, border=5, flag=wx.ALL)
        
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW)        
        self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP)
        self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP)

        self.dataGrid = DataGrid(self.panel, self.data_source.table)
        
        self.dataBox = wx.BoxSizer(wx.HORIZONTAL)        
        self.dataBox.Add(self.dataGrid, flag=wx.GROW)
        
        self.mainBox = wx.BoxSizer(wx.HORIZONTAL)
        self.mainBox.Add(self.vbox, flag=wx.LEFT | wx.GROW)
        self.mainBox.Add(self.dataBox, flag=wx.ALIGN_RIGHT)
        
        self.panel.SetSizer(self.mainBox)
        self.mainBox.Fit(self)
    
    def create_status_bar(self):
        self.statusbar = self.CreateStatusBar()

    def init_plot(self):
        self.dpi = 100
        self.fig = Figure((3.0, 3.0), dpi=self.dpi)

        self.axes = self.fig.add_subplot(111)
        self.axes.set_axis_bgcolor('black')
        self.axes.xaxis.set_major_formatter(mdates.DateFormatter(GraphFrame.DATE_FORMAT))
        
        pylab.setp(self.axes.get_xticklabels(), fontsize=6)
        pylab.setp(self.axes.get_yticklabels(), fontsize=6)


        self.axes.fmt_xdata = mdates.DateFormatter(GraphFrame.DATE_FORMAT)
        formatter = strpdate2num(GraphFrame.DATE_FORMAT)        
        self.colors = ['y', 'b', 'r', 'm']
        if not self.lines is None:
            n = 1
            for description in self.lines.keys() :
                tempMap = {}
                for key in self.lines[description].keys():
                    tempMap[formatter(key)] = self.lines[description][key]
                keys = []
                values = []
                for key in sorted(tempMap.iterkeys()):
                    keys.append(key)
                    values.append(tempMap[key])
                self.axes.xaxis_date()
                self.axes.plot(
                    keys,
                    values,
                    linewidth=1,
                    color=self.colors[n-1],
                    #color=(n % 2, (n % 3) % 2, (n % 2 + 1) % 2),
                    label = description,
                )
                n = n + 1
        prop = matplotlib.font_manager.FontProperties(size=7)
        self.axes.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15),
          ncol=2, fancybox=True, shadow=True, prop=prop)
        self.fig.autofmt_xdate()
        
    def draw_plot(self):
        """ Redraws the plot
        """
        # when xmin is on auto, it "follows" xmax to produce a 
        # sliding window effect. therefore, xmin is assigned after
        # xmax.
        #
        timestamps = [row[0] for row in self.data_source.table]
	formatter = strpdate2num(GraphFrame.DATE_FORMAT)        
	xmin = formatter(min(timestamps))
        xmax = formatter(max(timestamps))
        if self.xmax_control.is_auto():
            self.xmax = xmax
        else:
            self.xmax = xmin+((xmax-xmin)*int(self.xmax_control.manual_value())/100)
        if self.xmin_control.is_auto():            
            self.xmin = xmin
        else:
            self.xmin = xmin+((xmax-xmin)*float(self.xmin_control.manual_value())/100.0)
        if self.xmin<1:
            self.xmin = xmin

        # for ymin and ymax, find the minimal and maximal values
        # in the data set and add a mininal margin.
        # 
        # note that it's easy to change this scheme to the 
        # minimal/maximal value in the current display, and not
        # the whole data set.
        # 
	#        ymin = 0
	#        ymax = 100
        if self.ymin_control.is_auto():
            self.ymin = round(min(self.data), 0) - 1
        else:
            self.ymin = int(self.ymin_control.manual_value())
        
        if self.ymax_control.is_auto():
            self.ymax = round(max(self.data), 0) + 1
        else:
            self.ymax = int(self.ymax_control.manual_value())
            
        self.draw_plot_with_values(self.xmin, self.xmax, self.ymin, self.ymax)

    def draw_plot_with_values(self, xmin, xmax, ymin, ymax):

        #print "plot",xmin, xmax, ymin, ymax
        self.axes.set_xbound(lower=xmin, upper=xmax)
        self.axes.set_ybound(lower=ymin, upper=ymax) 
        
        # anecdote: axes.grid assumes b=True if any other flag is
        # given even if b is set to False.
        # so just passing the flag into the first statement won't
        # work.
        #
        if self.cb_grid.IsChecked():
            self.axes.grid(True, color='gray')
        else:
            self.axes.grid(False)

        # Using setp here is convenient, because get_xticklabels
        # returns a list over which one needs to explicitly 
        # iterate, and setp already handles this.
        #  
        pylab.setp(self.axes.get_xticklabels(), 
            visible=self.cb_xlab.IsChecked())
        
        #self.plot_data.set_xdata(np.arange(len(self.data)))
        #self.plot_data.set_ydata(np.array(self.data))

        self.canvas.draw()

	back_formatter = mdates.DateFormatter(GraphFrame.DATE_FORMAT)
	xmin = back_formatter(xmin)
	xmax = back_formatter(xmax)
	self.dataGrid.repaint(xmin, xmax, ymin, ymax)
    
    def on_pause_button(self, event):
        #self.paused = not self.paused
        self.on_redraw_timer(event)
    
#    def on_update_pause_button(self, event):
#        label = "Resume" if self.paused else "Pause"
#        self.pause_button.SetLabel(label)
    
    def on_click_down(self, event):
        self.last_down_x = event.X;
        self.last_down_y = event.Y;

    def on_click_up(self, event):
        canvas_size = self.canvas.GetSize()
        fig_width = self.fig.get_figwidth() * self.fig.get_dpi()
        fig_height = self.fig.get_figheight() * self.fig.get_dpi()
        start_x = (canvas_size.width - fig_width) / 2 
        end_x = fig_width + (canvas_size.width - fig_width) / 2
        start_y = (canvas_size.height - fig_height) / 2
        end_y = fig_height + (canvas_size.height - fig_height) / 2
	top = int(fig_height*0.1)
	bottom = int(fig_height*0.8)
	left = int(fig_width*0.12)
	right = int(fig_width*0.9)
        print event.X, event.Y
        if event.X>left and event.X<right and self.last_down_x>left and self.last_down_x<right and event.Y>top and event.Y<bottom and self.last_down_y>top and self.last_down_y<bottom:
            xmin=self.xmin+((self.xmax-self.xmin)*(float(min(event.X, self.last_down_x))-left)/(right-left))
            xmax=self.xmin+((self.xmax-self.xmin)*(float(max(event.X, self.last_down_x))-left)/(right-left))
                    
            ymin=float(min(bottom - event.Y, bottom - self.last_down_y))/(bottom-top)*(self.ymax-self.ymin)+self.ymin
            ymax=float(max(bottom - event.Y, bottom - self.last_down_y))/(bottom-top)*(self.ymax-self.ymin)+self.ymin
    
            self.draw_plot_with_values(xmin, xmax, ymin, ymax)
            
    def on_cb_grid(self, event):
        self.draw_plot()
    
    def on_cb_xlab(self, event):
        self.draw_plot()
    
    def on_save_plot(self, event):
        file_choices = "PNG (*.png)|*.png"
        
        dlg = wx.FileDialog(
            self, 
            message="Save plot as...",
            defaultDir=os.getcwd(),
            defaultFile="plot.png",
            wildcard=file_choices,
            style=wx.SAVE)
        
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.canvas.print_figure(path, dpi=self.dpi)
            self.flash_status_message("Saved to %s" % path)
    
    def on_redraw_timer(self, event):
        # if paused do not add data, but still redraw the plot
        # (to respond to scale modifications, grid change, etc.)
        #
        if not self.paused:
            self.data.append(self.datagen.next())
        
        self.draw_plot()
    
    def on_exit(self, event):
        self.Destroy()
    
    def flash_status_message(self, msg, flash_len_ms=1500):
        self.statusbar.SetStatusText(msg)
        self.timeroff = wx.Timer(self)
        self.Bind(
            wx.EVT_TIMER, 
            self.on_flash_status_off, 
            self.timeroff)
        self.timeroff.Start(flash_len_ms, oneShot=True)
    
    def on_flash_status_off(self, event):
        self.statusbar.SetStatusText('')


class DataGrid(wx.grid.Grid):
    def __init__(self, parent, table):
        wx.grid.Grid.__init__(self, parent, -1)
        self.data = table
        self.ymin = 0
        self.ymax = 100
        timestamps = [row[0] for row in self.data]
        self.xmin = min(timestamps)
        self.xmax = max(timestamps)
#        data = (("A", "B"), 
#                ("C", "D"), 
#                ("E", "F"), 
#                ("G", "G"),
#                ("F", "F"), 
#                ("Q", "Q"))
        self.colLabels = ("Timestamp", "Resource", "Value", "User", "Process")
        self.repaintGrid()
        
    def repaintGrid(self):
        self.repaint(self.xmin, self.xmax, self.ymin, self.ymax)
        
    def repaint(self, xmin, xmax, ymin, ymax):
        table = filter(lambda row : ymin <= row[2] <= ymax and xmin <= row[0] <= xmax, self.data)
	#print "grid",xmin, xmax, ymin, ymax
        rowLabels = range(len(table))
        rowLabels = tuple(map(lambda x : str(x), rowLabels))
        tableBase = GenericTable(table, rowLabels, self.colLabels)
        self.SetScrollbar(wx.VERTICAL, 10, 10, 10, True)   
        self.SetTable(tableBase)
        self.AutoSizeColumns()
        
class GenericTable(wx.grid.PyGridTableBase):
    def __init__(self, data, rowLabels=None, colLabels=None):
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data
        self.rowLabels = rowLabels
        self.colLabels = colLabels
        
    def GetNumberRows(self):
        return len(self.data)

    def GetNumberCols(self):
        return len(self.data[0])

    def GetColLabelValue(self, col):
        if self.colLabels:
            return self.colLabels[col]
            
    def GetRowLabelValue(self, row):
        if self.rowLabels:
            return self.rowLabels[row]
            
    def IsEmptyCell(self, row, col):
        return False

    def GetValue(self, row, col):
        return self.data[row][col]

    def SetValue(self, row, col, value):
        pass

        
if __name__ == '__main__':
    app = wx.PySimpleApp()
    app.frame = GraphFrame(None, '../../../test_data/chromi.log')
    app.frame.Show()
    app.MainLoop()
